package com.tpp.threat_perception_platform.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tpp.threat_perception_platform.dao.HotfixMapper;
import com.tpp.threat_perception_platform.dao.WinCveDbMapper;
import com.tpp.threat_perception_platform.param.MyParam;
import com.tpp.threat_perception_platform.pojo.Hotfix;
import com.tpp.threat_perception_platform.response.ResponseResult;
import com.tpp.threat_perception_platform.service.HotfixService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;
@Service
public class HotfixServiceImpl implements HotfixService {
    @Autowired
    private HotfixMapper hotfixMapper;
    @Autowired
    private WinCveDbMapper winCveDbMapper;
    @Override
    @Transactional
    public int saveHotfix(Hotfix hotfix) {
        int count = hotfixMapper.countByMacAddress(hotfix.getMacAddress());
        // 设置公共属性
        hotfix.setDetectTime(new Timestamp(System.currentTimeMillis()));
        // 插入新记录
        return hotfixMapper.insertSelective(hotfix);
    }

    @Override
    public void deleteByMacAddress(String macAddress) {
        hotfixMapper.deleteByMacAddress(macAddress);
    }

    @Override
    public ResponseResult hotfixList(MyParam param) {
        PageHelper.startPage(param.getPage(), param.getLimit());

        List<Hotfix> dataList;

        if (param.getMacAddress() != null && !param.getMacAddress().isEmpty()) {
            dataList = hotfixMapper.findByMacAddress(param);
        } else if (param.getHostName() != null && !param.getHostName().isEmpty()) {
            dataList = hotfixMapper.findByHostName(param);
        } else if (param.getHotfixId() != null && !param.getHotfixId().isEmpty()) {
            dataList = hotfixMapper.findByHotfixId(param);
        } else {
            dataList = hotfixMapper.findAll(param);
        }

        // 查询关联漏洞信息
        for (Hotfix hotfix : dataList) {
            List<String> cveList = winCveDbMapper.selectCveByKb(hotfix.getHotfixId());
            hotfix.setCveList(cveList);
        }

        PageInfo<Hotfix> pageInfo = new PageInfo<>(dataList);
        return new ResponseResult<>(pageInfo.getTotal(), pageInfo.getList());
    }

}
